package com.pt25.base.dep.shardingjdbc.datasource;


import lombok.Setter;

/**
 * 该类的作用是持有当前线程环境下的数据源，并切换数据源
 */
public class MultiDatasourceContext {

    private static final ThreadLocal<String> contextHolder = new InheritableThreadLocal<>();
    @Setter
    private static String defaultDatasource = null;

    /**
     * 设置数据源
     *
     */
    public static void setDataSource(String db) {
        contextHolder.set(db);
    }

    /**
     * 取得当前数据源
     *
     */
    public static String getDataSource() {
        String dataSource = contextHolder.get();
        if(null == dataSource){
            return defaultDatasource;
        }
        return dataSource;
    }

    /**
     * 清除上下文数据
     */
    public static void clear() {
        contextHolder.remove();
    }

}
